import React, {useEffect, useState} from 'react'
import {Button, Space, message, TreeSelect, Select} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {history, connect} from 'umi'
import {
	PlusOutlined,
	ArrowUpOutlined,
	ArrowDownOutlined,
} from '@ant-design/icons'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import Permissions from '@/components/Permissions'
import {
	getImportSupplierBidding,
	getSupplierBaseExcelList,
	getSupplierbiddingList,
} from '@/service/supplier/supplierbidding'
import {getOnlydept} from '@/service/common'
import {translateDataToTree} from '@/utils/common'
import {getDict} from '@/service/common/dict'
import CustomTable from '@/components/Table'
import BatchUpload from '@/components/BatchUpload'
import {modalApi} from '@/utils/modalReq'
import {downloadDocumentUrl} from '@/service/common/download'

interface DataType {
	id: string | string[] | null
	projectName: string
	biddingCode: string
	projectBudget: string
	leadingDeptId: string
	purchaseDeptId: string
	projectBidSection: string
	createArchivesTime: string
	createArchivesPerson: string
	updateTime: string
	projectStatus: string
}

const formItemLayout = {
	labelCol: {flex: '90px'},
	wrapperCol: {flex: '1'},
}

const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}

const bidding = (props: {user: {orgId: string | number}}) => {
	const [dataSourse, setDataSourse] = useState([])
	const [searchData, setSearchData] = useState({})
	const [deptSource, setDeptSource] = useState<any[]>([])
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	// 字典数据
	const [dictData, setDictData] = useState<any>({})
	const [loading, setLoading] = useState<boolean>(false)
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	/** 获取上级部门数据 */
	const onListFun = () => {
		getOnlydept({merchantId: props.user.orgId}).then((res: any) => {
			if (res?.data?.length) {
				const list = translateDataToTree(res.data)
				setDeptSource(list as any)
			}
		})
	}
	useEffect(() => {
		onListFun()
	}, [props.user.orgId])

	// 获取供应商招投标列表
	const getData = () => {
		setLoading(true)
		getSupplierbiddingList({...params, ...searchData})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				}
			})
			.catch((err) => {
				setDataSourse([])
				message.error(err)
				setLoading(false)
			})
	}
	useEffect(() => {
		getData()
	}, [params])
	useEffect(() => {
		getDict(
			{
				dictKeys: [
					'ZC_GYS',
					'JC_GYS',
					'CZ_GYS',
					'SP_GYS',
					'DYY_GYS',
					'CS_GYS',
					'Project_Status',
					'Project_Bid_Section',
					'Enterprise_Nature',
				],
			},
			(res: any) => {
				setDictData(res)
			},
		)
	}, [])

	/** 点击详情及编辑事件 */
	const onDetails = (type: string, record: DataType) => {
		history.push({
			pathname: `/supplier/bidding/${type}`,
			query: {
				id: record?.id,
			},
		})
	}

	const columns: ColumnsType<DataType> = [
		{
			title: '招标项目名称',
			dataIndex: 'projectName',
			align: 'center',
			width: 140,
			render: (text) => text || '-',
		},
		{
			title: '招标编号',
			dataIndex: 'biddingCode',
			align: 'center',
			width: 100,
			render: (text) => text || '-',
		},
		{
			title: '项目预算',
			dataIndex: 'projectBudget',
			align: 'center',
			width: 120,
			render: (text) => <>{text ? `${text}万元` : '-'}</>,
		},
		{
			title: '主导部门',
			dataIndex: 'leadingDeptName',
			align: 'center',
			width: 100,
			render: (text) => (
				<>
					{text ? (
						<TreeSelect
							value={text}
							dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
							disabled
							fieldNames={fieldNames}
							treeData={deptSource}
						/>
					) : (
						'-'
					)}
				</>
			),
		},
		{
			title: '采购部门',
			dataIndex: 'purchaseDeptName',
			align: 'center',
			width: 100,
			render: (text) => (
				<>
					{text ? (
						<TreeSelect
							value={text}
							dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
							disabled
							fieldNames={fieldNames}
							treeData={deptSource}
						/>
					) : (
						'-'
					)}
				</>
			),
		},
		{
			title: '标段',
			dataIndex: 'projectBidSection',
			align: 'center',
			width: 100,
			render: (text) => (
				<>
					{' '}
					{text ? (
						<Select
							disabled
							value={text}
							fieldNames={{value: 'dictKey', label: 'dictValue'}}
							options={dictData.Project_Bid_Section}
						/>
					) : (
						'-'
					)}
				</>
			),
		},
		{
			title: '建档时间',
			width: 150,
			dataIndex: 'createArchivesTime',
			align: 'center',
			render: (text) => text || '-',
		},
		{
			title: '建档人',
			width: 100,
			dataIndex: 'createArchivesPerson',
			align: 'center',
			render: (text) => text || '-',
		},
		{
			title: '最近更新时间',
			width: 180,
			dataIndex: 'updateTime',
			align: 'center',
		},
		{
			title: '项目状态',
			width: 100,
			dataIndex: 'projectStatus',
			align: 'center',
			render: (text) => (
				<Select
					disabled
					value={text}
					fieldNames={{value: 'dictKey', label: 'dictValue'}}
					options={dictData.Project_Status}
				/>
			),
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 170,
			render: (text: any, record) => (
				<Space size={12}>
					<Permissions permissionID="amc_supplier_bidding_view">
						<Button
							type="link"
							onClick={() => {
								onDetails('view', record)
							}}>
							招标详情
						</Button>
					</Permissions>
					<Permissions permissionID="amc_supplier_bidding_edit">
						<Button
							type="link"
							onClick={() => {
								onDetails('edit', record)
							}}>
							内容更新
						</Button>
					</Permissions>
				</Space>
			),
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '项目名称',
					name: 'projectName',
					key: 'projectName',
				},
				{
					type: 'select',
					label: '项目状态',
					name: 'projectStatus',
					key: 'projectStatus',
					keys: 'dictKey',
					title: 'dictValue',
					items: dictData.Project_Status,
				},
				{
					type: 'treeSelect',
					label: '采购部门',
					name: 'purchaseDeptId',
					key: 'purchaseDeptId',
					keys: 'id',
					title: 'name',
					defaultExpandAll: true,
					treeData: deptSource,
				},
			],
		},
	]
	const onFinish = (values: any) => {
		setSearchData(values)
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}

	const errorColumns: ColumnsType<DataType> = [
		{
			title: '招标项目名称',
			dataIndex: 'projectName',
			align: 'center',
		},
		{
			title: '项目状态',
			dataIndex: 'projectStatus',
			align: 'center',
		},
		{
			title: '标段',
			dataIndex: 'projectBidSection',
			align: 'center',
		},
		{
			title: '失败原因',
			dataIndex: 'message',
			align: 'center',
		},
	]

	return (
		<div className={styles.admittance}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
					/>
				</div>
				<div className={styles.btnlist}>
					<Space size={12}>
						<Permissions permissionID="amc_supplier_bidding_add">
							<Button
								icon={<PlusOutlined />}
								type="primary"
								ghost
								size="small"
								onClick={() => {
									history.push('/supplier/bidding/add')
								}}>
								新增项目
							</Button>
						</Permissions>
						<Permissions permissionID="amc_supplier_bidding_import">
							<Button
								icon={<ArrowUpOutlined />}
								className={styles.warning}
								ghost
								size="small"
								onClick={() => {
									setIsUploadModalOpen(true)
								}}>
								导入
							</Button>
						</Permissions>
						<Permissions permissionID="amc_supplier_bidding_export">
							<Button
								icon={<ArrowDownOutlined />}
								className={styles.import}
								ghost
								size="small"
								onClick={() => {
									downloadDocumentUrl({
										resourceId: '127',
										queryDesc:
											'供应商招投标导出,resourceId:127',
										queryParam: searchData,
									})
								}}>
								导出
							</Button>
						</Permissions>
					</Space>
				</div>
				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={getImportSupplierBidding}
				onTableList={getSupplierBaseExcelList}
				getListData={getData}
				downloadUrl="supplier/供应商招投标导入模板.xlsx"
				uploadFileUrl={`${modalApi.supplier}/supplierbidding/checkBiddingData`}
				columns={errorColumns}
				sourceId={31}
				templateType="供应商招投标导入模板"
			/>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(bidding)
